<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>编辑转换自借货订单的出库单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //是否临时保存
        var temporary = new Ext.form.Hidden({
          name: 'temporary',
          value: 0
        });
        
        //你要引用的订单类型
        var loanId = new Ext.form.Hidden({
          name: 'id',
          value:<%=params[:id]%>
        });

        var version = new Ext.form.Hidden({
          name: 'lock_version'
        });
        
        //备注
        var desc = new Ext.form.TextField({
          fieldLabel: '备注',
          name: 'description',
          anchor: '97%'
        });

        //所有供应商
        var toCustomer = new Ext.form.TextField({
          fieldLabel: '客户',
          name: 'customer_name',
          anchor: '95%',
          readOnly:true
        });
        
        //所有仓库
        var warehouseTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{number}|{name}', '</div></tpl>');
        var warehouseStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/warehouse/getAllWarehouse?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }])
        });

        var fromWarehouse = new Ext.form.ComboBox({
          store: warehouseStore,
          fieldLabel: '调出仓库',
          allowBlank: false,
          blankText: "产品必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'warehouse_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '95%',
          tpl: warehouseTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction:'all',
          selectOnFocus:true
        });

        //出库日期
        var actionDate = new Ext.form.DateField({
          fieldLabel: '出库日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "出库日期必须选择",
          emptyText: '请选择日期...',
          anchor: '90%'
        });

        var linkman = new Ext.form.TextField({
          fieldLabel: '联系人',
          name: 'linkman',
          anchor: '95%'
        });

        var phone = new Ext.form.TextField({
          fieldLabel: '电话',
          name: 'phone',
          anchor: '95%'
        });

        var address = new Ext.form.TextField({
          fieldLabel: '送货地址',
          name: 'delivery_address',
          anchor: '95%'
        });
        
        //--------------------------------------------------------------------------
        var productTemplate = new Ext.XTemplate('<tpl for="."><div  class="search-item"><div style="float:left; width:230px">{name}</div><div>', '{is_suit}', '</div></div></tpl>');
        var productStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/loan_delivery/getProductsForEdit"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'spec'
            }, {
              name: 'unit'
            }, {
              name: 'quantity'
            }, {
              name: 'balance_quantity'
            }, {
              name: 'stock_quantity'
            }, {
              name: 'description'
            }, {
              name: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //供应商产品
        var productCBB = new Ext.form.ComboBox({
          store: productStore,
          fieldLabel: '供应商产品',
          allowBlank: false,
          blankText: "产品必须选择",
          emptyText: '请选择...',
          //typeAhead: false,
          loadingText: '搜索中...',
          displayField: 'name',
          anchor: '90%',
          pageSize: 25,
          //hideTrigger: false,
          tpl: productTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });

        productCBB.on('select', function(combo, record, index) {
          var loanItemRecord = loanDetailsSM.getSelected();
          if (!loanItemRecord) {
            return false;
          }
          if (isDuplicateByProduct(loanDetailsDS,record.get('id'),loanItemRecord.id)){
            //删除当前记录
            if (loanItemRecord.get('product_id') != record.get('id')){
              loanDetailsDS.remove(loanItemRecord);
            }
          }else{
            if (loanItemRecord.get('product_id') != record.get('id')){
              loanItemRecord.set('number',record.get('number'));
              loanItemRecord.set('spec',record.get('spec'));
              loanItemRecord.set('unit',record.get('unit'));
              loanItemRecord.set('quantity',0);
              loanItemRecord.set('balance_quantity',record.get('balance_quantity'));
              loanItemRecord.set('stock_quantity',record.get('stock_quantity'));
              loanItemRecord.set('product_id',record.get('id'));
              //判断套装
              loanItemRecord.set('is_suit',record.get('is_suit'));
            }
          }
        });

        productCBB.on('focus', function(combo, record, index) {
          productStore.baseParams.loan_id = <%=@loanId%>;
          productStore.load();
        });
        //------------------------------------------------------------------------
        //入库Grid Store
        var loanDetailsDS = new Ext.data.Store({
          baseParams:{id:loanId.getValue()},
          proxy: new Ext.data.HttpProxy({
            url: '/loan_delivery/getDetailsBalanceByIdForEdit'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'loan_id'
            },{
              name: 'number'
            },{
              name: 'spec'
            },{
              name: 'product_name'
            }, {
              name: 'description'
            },{
              name: 'unit'
            },{
              name: 'quantity',
              type: 'int'
            },{
              name: 'balance_quantity',
              type: 'int'
            },{
              name: 'stock_quantity',
              type: 'int'
            },{
              name: 'product_id'
            },{
              name: 'description'
            }])
        });
        
        //生成产品Grid的CM
        var loanDetailsSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var loanDetailsCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),loanDetailsSM,{
              id: 'common',
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              editor:productCBB,
              width: 230
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 90
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 50
            },{
              header: '当前数量',
              align: 'right',
              dataIndex: 'quantity',
              editor: new Ext.form.NumberField({
                allowBlank: false,
                allowDecimals: false,
                allowNegative: false
              }),
              width: 75
            },{
              header: '可转数量',
              dataIndex: 'balance_quantity',
              align: 'right',
              width: 75
            },{
              header: '库存数量',
              dataIndex: 'stock_quantity',
              align: 'right',
              width: 75
            },{
              header: '备注',
              dataIndex: 'description',
              width: 95,
              editor:new Ext.form.TextField({
                name: 'description',
                anchor: '90%'
              })
            }
          ]});

        //采购订单的产品的Grid
        var loanDetailsGrid = new Ext.grid.EditorGridPanel({
          store: loanDetailsDS,
          cm: loanDetailsCM,
          sm: loanDetailsSM,
          width: 895,
          height: 350,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          clicksToEdit: 1,//这里应该是单击就可以修改的意思。因为默认是要双击的。
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                // access the Record constructor through the grid's store
                var Product = loanDetailsGrid.getStore().recordType;
                var productRecord = new Product({
                  product_name: '请选择产品'
                });
                loanDetailsGrid.stopEditing();
                loanDetailsDS.insert(0, productRecord);
                loanDetailsGrid.startEditing(0, 0);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var record = loanDetailsSM.getSelected();
                if (!record) {
                  return false;
                }
                loanDetailsDS.remove(record);
              }
            }]
        });

        //暂时保存按钮
        var submitButton = new Ext.Button({
          text: '提交出库',
          iconCls: 'icon-save',
          handler: function(){
            //saveWarehousingEntry("save");
            if(deliveryFromLoanFormPanel.form.isValid()){
              var productsJsonStr = gridStoreToJson(loanDetailsDS,rejectKeyArray);
              if (loanDetailsDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = deliveryFromLoanFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/loan_delivery/update',
                success : function (result, request) {
                  if (Ext.util.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "保存借货出库单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.util.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  editLoanDeliveryFromLoanWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editLoanDeliveryFromLoanWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //临时保存按钮
        var tempSaveButton = new Ext.Button({
          text: '预备出库',
          tooltip: '暂时保存借货订单。',
          iconCls: 'temp-save',
          handler: function(){
            //首先把临时变量设置为1
            temporary.setValue(1);
            //saveWarehousingEntry("save");
            if(deliveryFromLoanFormPanel.form.isValid()){
              var productsJsonStr = gridStoreToJson(loanDetailsDS,rejectKeyArray);
              if (loanDetailsDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = deliveryFromLoanFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/loan_delivery/update',
                success : function (result, request) {
                  if (Ext.util.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "保存借货出库单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.util.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  editLoanDeliveryFromLoanWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editLoanDeliveryFromLoanWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });
        
        //
        var closeButton = new Ext.Button({
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            editLoanDeliveryFromLoanWin.destroy();
          }
        });
        
        var deliveryFromLoanFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'delivery_form',
          labelWidth: 55,
          width: '900',
          labelAlign: 'right',
          frame : true,
          //defaultType: 'textfield',
          url : '/loan_delivery/update',
          method: 'GET',
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'linkman'
            }, {
              name: 'phone'
            }, {
              name: 'delivery_address'
            }, {
              name: 'customer_name',
              mapping: 'customer.name'
            }, {
              name: 'warehouse_id'
            }, {
              name: 'action_date',
              type: 'date',
              dateFormat: 'Y/m/d'
            }, {
              name: 'description'
            }, {
              name: 'lock_version'
            }]),
          items: [{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .4,
                  layout: 'form',
                  border: false,
                  items: [toCustomer]
                }, {
                  columnWidth: .3,
                  layout: 'form',
                  border: false,
                  items: [fromWarehouse]
                }, {
                  columnWidth: .3,
                  layout: 'form',
                  border: false,
                  items: [actionDate]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .15,
                  layout: 'form',
                  border: false,
                  items: [linkman]
                }, {
                  columnWidth: .25,
                  layout: 'form',
                  border: false,
                  items: [phone]
                }, {
                  columnWidth: .6,
                  layout: 'form',
                  border: false,
                  items: [address]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [desc]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [loanDetailsGrid]
                }]
            },loanId,temporary,version],
          buttons: [submitButton,tempSaveButton,closeButton]
        });
        
        deliveryFromLoanFormPanel.render('delivery_form');
        //
        loanDetailsDS.load();
        loanDetailsGrid.on('afteredit', afterEdit, this );

        function afterEdit(obj) {
          
          if(obj.field=="quantity"){
            if (obj.record.get('quantity') > obj.record.get('balance_quantity') || obj.record.get('quantity')  == 0){
              obj.record.set('quantity', obj.record.get('balance_quantity'));
              return;
            }
          }
        }

        warehouseStore.load({callback: function(record, options, success){
            if(success){
              deliveryFromLoanFormPanel.form.load({
                url: '/loan_delivery/getLoanDeliveryById?id=' + <%=params[:id]%>,
                method : 'GET',
                waitMsg: '正在载入数据...',
                success: function(form, action){
                },
                failure: function(form, action){
                  Ext.MessageBox.alert('提示信息', '信息加载失败');
                }
              });
            }else{
              Ext.Msg.alert('操作','失败！');
            }
          }});
        
      })
    </script>
  </head>
  <body>
    <div id="delivery_form"></div>
  </body>
</html>
